/*
 * Copyright (C) 2015 truth
 *
 * This program is non-free software, but you can redistribute it and/or modify
 * it if you are in hjj(Huangshi Hejianjiao) team.
 */
package com.truthbean.jutils.dao.utils;

import java.sql.Connection;

import com.truthbean.jutils.exception.ExceptionUtils;

/**
 * @since Jan 15, 2015 11:19:45 AM
 * @author TruthBean
 */
public class DBContext {

    private DBContext() {
    }

    private static DBContext instance = new DBContext();

    public static DBContext getInstance() {
        return instance;
    }

    /**
     * 实例化一个线程
     */
    private final ThreadLocal<Connection> conThread = new ThreadLocal<>();

    /**
     * 将数据连接绑定线程，有利于并发操作
     * @param conn
     */
    public void bind(Connection conn) {
        if (conThread != null) {
            conThread.set(conn);
        }
        ExceptionUtils.throwIfNull(conn, "Connection 为空");
    }

    /**
     * 从当前运行线程中获取与其绑定的数据连接
     * @return 
     */
    public Connection get() {
        if (conThread != null) {
            return conThread.get();
        }
        ExceptionUtils.throwIfNull(conThread, "ThreadLocal 为空");
        return null;
    }

    public void remove() {
        if (conThread != null) {
            conThread.remove();
        }
        ExceptionUtils.throwIfNull(conThread, "ThreadLocal 为空");
    }
}
